/**
 * 红包任务调度
 */
import { scheduleJob, RecurrenceRule, Range } from 'node-schedule'
import { WEBSOCKETS, toSuccess, useEntityManager } from '@sker/core'
import { AutoDeviceWork, AutoRed2, AutoRedLog } from '@sker/entities'
import dayjs from 'dayjs'
import { container } from 'tsyringe'
import { Between } from 'typeorm'
export default async () => {

    const rule = new RecurrenceRule();
    rule.second = new Range(0, 59, 10); // 设置每10秒执行一次

    scheduleJob('RED_PACKAGE_SEND', '*/2 * * * *', async (fireData) => {
        await useEntityManager(async m => {
            const start = dayjs().add(20, 'second').toDate()
            const end = dayjs().add(60 * 2, 'second').toDate()
            const item = await m.findOne(AutoRed2, { where: { open_time: Between(start, end) }, order: { count: 'desc' } })
            if (item) {
                const sockets = container.resolve(WEBSOCKETS)
                sockets.forEach(socket => {
                    const pkg = Math.random() > 0.5 ? 'com.smile.gifmaker' : `com.kuaishou.nebula`
                    socket.send(JSON.stringify({
                        type: `CLOUD_CODE`,
                        payload: {
                            code: `home();sleep(1000);setClip('${item.link};app.launchPackage('${pkg}');')`,
                            id: `JOIN_RED_HOME`,
                            loopTimes: 0,
                            interval: 0,
                            delay: 0
                        }
                    }))
                })
            }
        })
    })
    scheduleJob('RED_PACKAGE_SEND', rule, async (fireData) => {
        console.log(fireData)
        await useEntityManager(async m => {
            const start = 30;
            const end = 60 * 10;
            const date = dayjs().format('YYYY-MM-DD')
            const list: any[] = await m.createQueryBuilder()
                .select('count', 'count')
                .addSelect('link', 'link')
                .addSelect('online', 'online')
                .addSelect('open_date', 'open_date')
                .addSelect('id', 'id')
                .addSelect('can_join', 'can_join')
                .from(AutoRedLog, 'log')
                .where('open_date>:start_date and open_date<:end_date', {
                    start_date: dayjs().add(start, 'second').toDate(),
                    end_date: dayjs().add(end, 'second').toDate()
                })
                .andWhere('can_join>:can_join', { can_join: 0 })
                .orderBy('count', 'DESC')
                .execute();
            if (list.length > 0) {
                const item = list[0];
                const deviceList = await m.find(AutoDeviceWork, { where: { date: date }, order: { mood: 'DESC' }, take: 3 })
                if (deviceList.length > 0) {
                    const websockets = container.resolve(WEBSOCKETS)
                    deviceList.map(it => {
                        const socket = websockets.get(it.uuid)
                        socket.send(JSON.stringify({ type: "RED_PACKET_JOIN", payload: item }))
                    })
                }
            }
        })
    })
    return toSuccess(true)
}
